package vn.cuhanh.dialog;

import org.json.JSONException;
import org.json.JSONObject;

import vn.cuhanh.BaseActivity;
import vn.cuhanh.GameDetailActivity;
import vn.cuhanh.MainActivity;
import vn.cuhanh.R;
import vn.cuhanh.fragment.AwardFragment;
import vn.cuhanh.utils.CuhanhDao;
import vn.cuhanh.utils.HelperFunc;
import vn.cuhanh.utils.LoginHelper;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class UpdatePhoneNoDialog extends Activity {
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register_phone_no);
		Button btnSave = (Button) findViewById(R.id.rating_dialog_btn_save);
		btnSave.setText(R.string.save);
		Button btnClose = (Button) findViewById(R.id.rating_dialog_btn_close);
		btnClose.setText(R.string.close);
//		btnClose.setBackground(getResources().getDrawable(R.drawable.btn_grey_bg));
		btnClose.setBackgroundResource(R.drawable.btn_grey_bg);
		btnSave.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Thread thread = new Thread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						updatePhoneNo();
					}
				});
				thread.start();
			}
		});
		btnClose.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onBackPressed();
			}
		});
		EditText editText = (EditText)findViewById(R.id.phone_no_edit_text);
		TelephonyManager phoneManager = (TelephonyManager) 
			    getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
		String phoneNumber = phoneManager.getLine1Number();
		editText.setText(phoneNumber);
	}	
	
	public void updatePhoneNo() {
		final String phoneNo = ((EditText)findViewById(R.id.phone_no_edit_text)).getText().toString();
		if(phoneNo == null || phoneNo.isEmpty()) {
			
			return;
		}
		if(!MainActivity.isLogin || MainActivity.username == null || MainActivity.username.isEmpty()) {
			LoginHelper loginHelper = LoginHelper.getInstance();
			loginHelper.requestZingMeLogin(this, new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					GameDetailActivity.forceRestartOnResume = true;
					sendUpdatePhoneNoRequest(phoneNo);
				}
			});
			return;
		}
		sendUpdatePhoneNoRequest(phoneNo);
	}
	
	public void showErrorMessage(int messageId) {
		showErrorMessage(getResources().getString(messageId));
	}
	
	public void showErrorMessage(final String message) {
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				HelperFunc.showSimpleAlertDialog(
						UpdatePhoneNoDialog.this, 
						getResources().getString(R.string.update_phone_no_fail_alert_title), 
						message, 
						getResources().getString(R.string.bt_cancel_title), 
						null, null, null, true);
			}
		});
	}
	
	public void showSuccessMessage(final boolean haveChange, final String message) {
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				HelperFunc.showSimpleAlertDialog(
						UpdatePhoneNoDialog.this, 
						getResources().getString(R.string.update_phone_no_success_alert_title), 
						message, 
						getResources().getString(R.string.bt_ok_title), 
						new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								Intent intent = new Intent();
								intent.putExtra("haveChange", haveChange);
								setResult(RESULT_OK, intent);
								finish();
							}
						}, null, null, true);
			}
		});
	}
	
	public void sendUpdatePhoneNoRequest(final String phoneNo) {
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String response = HelperFunc.getDataFromSv(getResources().getString(R.string.updatePhoneNoUrl)
						.replace("user_name", MainActivity.username)
						.replace("phone_no", phoneNo));
				if(response == null) {
					// show message
					showErrorMessage(R.string.no_network_2);
					return;
				}
				try {
					JSONObject jsonRes = new JSONObject(response);
					int result = jsonRes.getInt("result");
					switch (result) {
					case 1: // success
						int gainScore = jsonRes.getInt("gainScore");
						String message = "";
						if(gainScore == 1) {
							int score = jsonRes.getInt("score");
							int totalScore = jsonRes.getInt("totalScore");
							BaseActivity.updateTotalScore(UpdatePhoneNoDialog.this, totalScore, null);
							if(jsonRes.has("remainScore") && !jsonRes.isNull("remainScore")) {
								AwardFragment.remainDndScore = jsonRes.getInt("remainScore");
							}
							message = getResources().getString(R.string.update_phone_no_success_gain_score_alert_message)
									.replace("score", String.valueOf(score));
						} else {
							message = getResources().getString(R.string.update_phone_no_success_alert_message);
						}
						showSuccessMessage(true, message);
						CuhanhDao.updateSingleAccountField(UpdatePhoneNoDialog.this, MainActivity.username, "phoneNo", phoneNo);
						if(MainActivity.userAccount != null) {
							MainActivity.userAccount.setPhoneNo(phoneNo);
						}
						break;
					case -1: //invalid userName
						showErrorMessage(R.string.unknown_error);
						break;
					case -2: //invalid phoneNo
						showErrorMessage(R.string.invalid_phone_no_message);
						break;
					case -3: //user doer not exist
						showErrorMessage(R.string.unknown_error);
						break;
					case -4: //no change
						showSuccessMessage(false, getResources().getString(R.string.update_phone_no_success_alert_message));
						break;
					case 23000: //phone no has been used
						showErrorMessage(R.string.phone_no_has_been_used);
						break;
					default: //unknown error (case 0:)
						showErrorMessage(R.string.unknown_error);
						break;
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		thread.start();
	}
	
	@Override
	public void onBackPressed() {
		setResult(RESULT_CANCELED);
		finish();
	}
}
